package com.liu.case2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;

public class SocketSender implements Runnable{

    DatagramSocket socket = null;
    BufferedReader reader = null;

    private Integer port;
    private final String ip;
    private final Integer portTarget;

    public SocketSender(Integer port, String ip, Integer portTarger) {

        this.port = port;
        this.ip = ip;
        this.portTarget = portTarger;

        try {

            socket = new DatagramSocket(port);
            reader = new BufferedReader(new InputStreamReader((System.in)));

        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {

        while (true) {

            try {
                String dataline = reader.readLine();

                byte[] datapacket = dataline.getBytes(StandardCharsets.UTF_8);

                DatagramPacket packet = new DatagramPacket(datapacket,0,datapacket.length,new InetSocketAddress(this.ip,this.portTarget));

                socket.send(packet);

                if (dataline.equals("End!"))
                    break;

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        socket.close();
    }
}
